﻿using System;
using System.Collections.Generic;

namespace Wrox.ProCSharp.Generics
{
  public static class Algorithms
  {
    public static decimal AccumulateSimple(IEnumerable<Account> source)
    {
      decimal sum = 0;
      foreach (Account a in source)
      {
        sum += a.Balance;
      }
      return sum;
    }
        //带约束的泛型方法,指定source对象中的元素必须继承自IAccount接口
    public static decimal Accumulate<TAccount>(IEnumerable<TAccount> source)
        where TAccount : IAccount
    {
      decimal sum = 0;

      foreach (TAccount a in source)
      {
        sum += a.Balance;
      }
      return sum;
    }
        //带委托的泛型方法，拓展了Accumulate方法的可能方式
        //泛型委托Func<T1, T2, T2> action，前面两个参数T1，T2是输入参数，后一个参数T2是返回类型
    public static T2 Accumulate<T1, T2>(IEnumerable<T1> source, Func<T1, T2, T2> action)
    {
      T2 sum = default(T2);
      foreach (T1 item in source)
      {
        sum = action(item, sum);
      }
      return sum;
    }
  }
}
